import { ISubmitData, Method } from './type'
import axios from 'axios'
import router from '@/router'
import useUserStore from '@/store/modules/user'

const baseURL = import.meta.env.VITE_BASE_URL
const timeout = 30000

const service = axios.create({
  baseURL,
  timeout
})

service.interceptors.request.use(
  (config) => {
    const { profile } = useUserStore()
    const { token } = profile
    if (token) {
      config.headers!.Authorization = `Bearer ${token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

service.interceptors.response.use(
  (response) => {
    return response.data
  },
  (err) => {
    //需要登录
    if (err.response?.status === 401) {
      const { resetProfile } = useUserStore()
      resetProfile()
      const currentRoutePath = encodeURIComponent(
        router.currentRoute.value.fullPath
      )
      router.push(`/login?redirectUrl=${currentRoutePath}`)
    }
    return Promise.reject(err)
  }
)

const request = <T, R>(
  url: string,
  method: Method,
  submitData?: ISubmitData,
  baseURL?: string
) => {
  return service.request<T, R>({
    url,
    method,
    [method === 'get' ? 'params' : 'data']: submitData,
    baseURL
  })
}

export default request
